package com.im.service.contract.smo;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.im.service.contract.dao.IContractClauseQueryDAO;
import com.im.service.dto.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.im.service.contract.dao.IContractItemChangeQueryDAO;
import com.im.service.contract.dao.IContractItemQueryDAO;
import com.im.service.contract.dao.IContractQueryDAO;
import com.im.service.fundPlan.dao.IFundPlanQueryDAO;
import com.im.service.model.ContractAndItemVo;
import com.im.service.model.ContractProjectInfoVo;
import com.im.service.purchasePlan.dao.IPurchasePlanQueryDAO;
import com.im.util.JsonUtil;

import net.sf.json.JSONObject;

@Service
public class ContractQuerySMOImpl implements IContractQuerySMO {
	@Autowired
	private IContractQueryDAO contractQueryDAO;
	@Autowired
	private IContractItemQueryDAO contractItemQueryDAO;
	@Autowired
	private IContractItemChangeQueryDAO contractItemChangeQueryDAO;
	@Autowired
	private IPurchasePlanQueryDAO purchasePlanQueryDAO;
	@Autowired
	private IFundPlanQueryDAO fundPlanQueryDAO;
	@Autowired
	private IContractClauseQueryDAO contractClauseQueryDAO;

	@Override
	public PageQuery2<Contract> queryContractList(String jsonStr) {
		// 1.json格式校验
		if (!JsonUtil.jsonValidate(jsonStr)) {
			throw new BaseException(new StringBuffer().append("字符串： ").append(jsonStr).append("不符合JSON格式").toString());
		}
		PageQuery2<Contract> page = JsonUtil.jsonToBean(jsonStr, PageQuery2.class);
		Contract contract = JsonUtil.jsonToBean(jsonStr, Contract.class);

		Map<String, Object> param = new HashMap<String, Object>();
		param.put("contract", contract);
		param.put("page", page);
		PageHelper.startPage(page.getPageNumber(), page.getPageSize());
		List<Contract> list = contractQueryDAO.queryContractList(param);
		if (list != null && list.size() > 0)
			getFile(list);
		page.setRows(list);
		page.setTotalPages(((Page<Contract>) list).getPages());
		page.setTotal(((Page<Contract>) list).getTotal());
		//合计数据
		BigDecimal prepayTotals = new BigDecimal(0);
		BigDecimal moneys = new BigDecimal(0);
		for(Contract ctt : list) {
			if(ctt.getPrepayTotal() != null && !"".equals(ctt.getPrepayTotal())) {
				prepayTotals = prepayTotals.add(new BigDecimal(ctt.getPrepayTotal()));
			}
			if(ctt.getMoney() != null && !"".equals(ctt.getMoney())) {
				moneys = moneys.add(new BigDecimal(ctt.getMoney()));
			}
		}
		Map<String, String> foot = new HashMap<String, String>();
		foot.put("purchPlanNum", "合计");
		foot.put("prepayTotal", prepayTotals.setScale(4, BigDecimal.ROUND_HALF_UP).toString());
		foot.put("money", moneys.setScale(4, BigDecimal.ROUND_HALF_UP).toString());
		page.addFoot(foot);

		return page;
	}

	public void getFile(List<Contract> list) {
		for (Contract contract : list) {
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("uploadObjId", contract.getContractId());
			param.put("uploadObjType", "180");
			contract.setPerformanceFiles(fundPlanQueryDAO.queryFileListUploadsByCond(param));
			param.put("uploadObjType", "190");
			contract.setExpectFiles(fundPlanQueryDAO.queryFileListUploadsByCond(param));
			param.put("uploadObjType", "200");
			contract.setElectronFiles(fundPlanQueryDAO.queryFileListUploadsByCond(param));
		}
	}

	public PageQuery<ContractAndItemVo> queryCanChangeContractItemChangeList(String jsonStr) {
		// 1.json格式校验
		if (!JsonUtil.jsonValidate(jsonStr)) {
			throw new BaseException(new StringBuffer().append("字符串： ").append(jsonStr).append("不符合JSON格式").toString());
		}
		PageQuery<ContractAndItemVo> page = JsonUtil.jsonToBean(jsonStr, PageQuery.class);
		ContractAndItemVo contractItem = JsonUtil.jsonToBean(jsonStr, ContractAndItemVo.class);

		Map<String, Object> param = new HashMap<String, Object>();
		param.put("contractItem", contractItem);
		param.put("page", page);
		PageHelper.startPage(page.getPageNumber(), page.getPageSize());
		// 1、查询合同分项列表
		List<ContractAndItemVo> list = contractItemQueryDAO.queryCanChangeContractItemList(param);
		List<ContractAndItemVo> newlist = new ArrayList<ContractAndItemVo>();
		List<ContractAndItemVo> addchangelist = new ArrayList<ContractAndItemVo>();
		String contractClauseId = null;
		Boolean addflag = true;
		for (ContractAndItemVo item : list) {
			String contractItemId = item.getContractItemId();
				if (addflag) {
				contractClauseId = item.getContractClauseId();
				List<ContractItemChange> addlist = contractItemChangeQueryDAO
						.queryAddChangeListByContractClauseId(contractClauseId);
				if (addlist != null && addlist.size() > 0) {
					for (ContractItemChange contractItemChange : addlist) {
						ContractAndItemVo clonevo = (ContractAndItemVo) item.clone();
						clonevo.setContractItemName(contractItemChange.getContractItemName());
						clonevo.setAmount(contractItemChange.getAmount());
						clonevo.setUnitPrice(contractItemChange.getUnitPrice());
						clonevo.setItemTotal(contractItemChange.getTotal());
						clonevo.setDescription(contractItemChange.getDescription());
						clonevo.setOtherCharge(contractItemChange.getOtherCharge());
						clonevo.setStatusCd(contractItemChange.getStatusCd());
						clonevo.setStatus(contractItemChange.getStatus());
						clonevo.setDeleteflag("1");
						clonevo.setContItemChangeId(contractItemChange.getContItemChangeId());
						Map<String, Object> fileparam = new HashMap<String, Object>();
						fileparam.put("uploadObjId", clonevo.getContItemChangeId());
						fileparam.put("uploadObjType", "170");
						clonevo.setFiles(fundPlanQueryDAO.queryFileListUploadsByCond(fileparam));
						addchangelist.add(clonevo);
						}
					}
					addflag = false;
				}
			if (!contractClauseId.equals(item.getContractClauseId())) {
				newlist.addAll(addchangelist);
				addchangelist.clear();
				addflag = true;
			}

			// 2、查询变更数据
				Map<String, Object> changeparam = new HashMap<String, Object>();
				changeparam.put("contractItemId", contractItemId);
			changeparam.put("status", new String[] { "10", "20" });
				List<ContractItemChange> changelist = contractItemChangeQueryDAO
						.queryContractItemChangeList(changeparam);
				if (changelist.size() > 0) {
				if (changelist.size() == 1) {
					ContractItemChange newChange = changelist.get(0);
					// newlist.add((ContractAndItemVo) item.clone());
					// for (ContractItemChange contractItemChange : changelist)
					// {
					// if
					// (contractItemChange.getContItemChangeId().indexOf("_2") >
					// -1) {
					// newChange = contractItemChange;
					// }
					// }
					item.setContractItemName(newChange.getContractItemName());
					item.setUnitPrice(newChange.getUnitPrice());
					// item.setAmount(newChange.getAmount());
					item.setAmount(item.getAmount() + newChange.getAmount());
					item.setItemTotal(item.getItemTotal().add(newChange.getTotal()));
					// item.setItemTotal(newChange.getTotal());
					item.setOtherCharge(item.getOtherCharge().add(newChange.getOtherCharge()));
					// item.setOtherCharge(newChange.getOtherCharge());
					item.setDescription(newChange.getDescription());
					item.setContItemChangeId(newChange.getContItemChangeId());
					item.setStatusCd(newChange.getStatusCd());
					item.setStatus(newChange.getStatus());
					item.setDeleteflag("1");
					}
				// if (changelist.size() == 1) {
				// ContractItemChange voChange = changelist.get(0);
				// item.setContractItemName(voChange.getContractItemName());
				// item.setAmount(voChange.getAmount());
				// item.setUnitPrice(voChange.getUnitPrice());
				// item.setItemTotal(voChange.getTotal());
				// item.setDescription(voChange.getDescription());
				// item.setOtherCharge(voChange.getOtherCharge());
				// item.setStatusCd(voChange.getStatusCd());
				// item.setStatus(voChange.getStatus());
				// item.setDeleteflag("1");
				// item.setContItemChangeId(voChange.getContItemChangeId());
				// }
				newlist.add(item);
				} else {
					newlist.add(item);
				}
		}
		if (!addflag) {
			newlist.addAll(addchangelist);
			addchangelist.clear();
			addflag = true;
		}
		PageInfo pageInfo = new PageInfo(newlist);
		page.setRows(newlist);
		page.setTotalPages(pageInfo.getPages());
		page.setTotal(pageInfo.getTotal());
		return page;
	}

	public PageQuery<ContractAndItemVo> queryChangeExamineList(String jsonStr) {
		// 1.json格式校验
		if (!JsonUtil.jsonValidate(jsonStr)) {
			throw new BaseException(new StringBuffer().append("字符串： ").append(jsonStr).append("不符合JSON格式").toString());
		}
		PageQuery<ContractAndItemVo> page = JsonUtil.jsonToBean(jsonStr, PageQuery.class);
		ContractAndItemVo searchitem = JsonUtil.jsonToBean(jsonStr, ContractAndItemVo.class);
		JSONObject jsonObj = JSONObject.fromObject(jsonStr);
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("contractItem", searchitem);
		param.put("page", page);
		PageHelper.startPage(page.getPageNumber(), page.getPageSize());
		List<ContractAndItemVo> list = contractItemChangeQueryDAO.queryChangeExamineList(param);
		List<ContractAndItemVo> newlist = new ArrayList<ContractAndItemVo>();
		for (ContractAndItemVo item : list) {
			String contractItemId = item.getContractItemId();
			Map<String, Object> changeparam = new HashMap<String, Object>();
			changeparam.put("contractItemId", contractItemId);
			changeparam.put("status", new String[] { "10" });
			List<ContractItemChange> changelist = contractItemChangeQueryDAO.queryContractItemChangeList(changeparam);
			if (changelist.size() > 0) {
				// if (changelist.size() == 2) {
				// ContractItemChange oldChange = null;
				// ContractItemChange newChange = null;
				// for (ContractItemChange contractItemChange : changelist) {
				// if (contractItemChange.getContItemChangeId().indexOf("_1") >
				// -1) {
				// oldChange = contractItemChange;
				// }
				// if (contractItemChange.getContItemChangeId().indexOf("_2") >
				// -1) {
				// newChange = contractItemChange;
				// }
				// }
				// item.setOldamount(-oldChange.getAmount());
				// item.setOldunitPrice(oldChange.getUnitPrice());
				// item.setOlditemTotal(oldChange.getTotal().abs());
				// item.setOlddescription(oldChange.getDescription());
				// item.setOldotherCharge(oldChange.getOtherCharge().abs());
				// item.setAmount(newChange.getAmount());
				// item.setUnitPrice(newChange.getUnitPrice());
				// item.setItemTotal(newChange.getTotal());
				// item.setDescription(newChange.getDescription());
				// item.setOtherCharge(newChange.getOtherCharge());
				// item.setContractItemName(newChange.getContractItemName());
				// item.setContItemChangeId(newChange.getContItemChangeId());
				// item.setContractItemName(newChange.getContractItemName());
				// }
				if (changelist.size() == 1) {
					ContractItemChange voChange = changelist.get(0);
					item.setContractItemName(voChange.getContractItemName());
					item.setAmount(voChange.getAmount());
					item.setUnitPrice(voChange.getUnitPrice());
					item.setItemTotal(voChange.getTotal());
					item.setDescription(voChange.getDescription());
					item.setOtherCharge(voChange.getOtherCharge());
					item.setContractItemName(voChange.getContractItemName());
					item.setContItemChangeId(voChange.getContItemChangeId());
				}
				newlist.add(item);
			}
		}
		PageInfo pageInfo = new PageInfo(newlist);
		page.setRows(newlist);
		page.setTotalPages(pageInfo.getPages());
		page.setTotal(pageInfo.getTotal());
		return page;
	}

	public PageQuery<ContractAndItemVo> queryContractItemList(String jsonStr) {
		// 1.json格式校验
		if (!JsonUtil.jsonValidate(jsonStr)) {
			throw new BaseException(new StringBuffer().append("字符串： ").append(jsonStr).append("不符合JSON格式").toString());
		}
		PageQuery<ContractAndItemVo> page = JsonUtil.jsonToBean(jsonStr, PageQuery.class);
		ContractAndItemVo contractItem = JsonUtil.jsonToBean(jsonStr, ContractAndItemVo.class);

		Map<String, Object> param = new HashMap<String, Object>();
		param.put("contractItem", contractItem);
		param.put("page", page);
		PageHelper.startPage(page.getPageNumber(), page.getPageSize());
		List<ContractAndItemVo> list = contractItemQueryDAO.queryContractItemList(param);
		page.setRows(list);
		page.setTotalPages(((Page<ContractAndItemVo>) list).getPages());
		page.setTotal(((Page<ContractAndItemVo>) list).getTotal());
		return page;
	}

	@Override
	public Contract queryContractdetail(Contract contract) {
		Contract vo = contractQueryDAO.queryContractDetail(contract);
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("uploadObjId", vo.getContractId());
		param.put("uploadObjType", "180");
		vo.setPerformanceFiles(fundPlanQueryDAO.queryFileListUploadsByCond(param));
		param.put("uploadObjType", "190");
		vo.setExpectFiles(fundPlanQueryDAO.queryFileListUploadsByCond(param));
		param.put("uploadObjType", "200");
		vo.setElectronFiles(fundPlanQueryDAO.queryFileListUploadsByCond(param));
		return vo;
	}

	public ContractAndItemVo queryContractItemDetail(String jsonStr) {
		// 1.json格式校验
		if (!JsonUtil.jsonValidate(jsonStr)) {
			throw new BaseException(new StringBuffer().append("字符串： ").append(jsonStr).append("不符合JSON格式").toString());
		}
		JSONObject jsonObj = JSONObject.fromObject(jsonStr);
		String errorMsg = "获取查询合同分项详情入参时：";
		String conItemId = JsonUtil.getNotNullStringFromJSON(jsonObj, "conItemId", errorMsg);
		String contractItemId = JsonUtil.getNotNullStringFromJSON(jsonObj, "contractItemId", errorMsg);
		String contItemChangeId = JsonUtil.getStringFromJSON(jsonObj, "contItemChangeId", errorMsg);
		ContractAndItemVo vo = new ContractAndItemVo();
		vo.setConItemId(conItemId);
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("contractItem", vo);
		ContractAndItemVo item = contractItemQueryDAO.queryContractItemDetail(param);
		Map<String, Object> changeparam = new HashMap<String, Object>();
		// changeparam.put("contractItemId", contractItemId);
		changeparam.put("contItemChangeId", contItemChangeId);
		changeparam.put("status", new String[] { "10", "20" });
		List<ContractItemChange> changelist = contractItemChangeQueryDAO.queryContractItemChangeList(changeparam);
		if (changelist.size() > 0) {
		if (changelist.size() == 2) {
				ContractItemChange newChange = null;
				for (ContractItemChange contractItemChange : changelist) {
					if (contractItemChange.getContItemChangeId().indexOf("_2") > -1) {
						newChange = contractItemChange;
					}
				}
				item.setAmount(newChange.getAmount());
				item.setUnitPrice(newChange.getUnitPrice());
				item.setItemTotal(newChange.getTotal());
				item.setDescription(newChange.getDescription());
				item.setOtherCharge(newChange.getOtherCharge());
				item.setContItemChangeId(newChange.getContItemChangeId());
				item.setContractItemName(newChange.getContractItemName());
				}
		if (changelist.size() == 1) {
				ContractItemChange voChange = changelist.get(0);
				item.setContractItemName(voChange.getContractItemName());
				item.setAmount(voChange.getAmount());
				item.setUnitPrice(voChange.getUnitPrice());
				item.setItemTotal(voChange.getTotal());
				item.setDescription(voChange.getDescription());
				item.setOtherCharge(voChange.getOtherCharge());
				item.setContItemChangeId(voChange.getContItemChangeId());

			}
		}
		if (StringUtils.isNotBlank(contItemChangeId)) {
			Map<String, Object> fileparam = new HashMap<String, Object>();
			fileparam.put("uploadObjId", contItemChangeId);
			fileparam.put("uploadObjType", "170");
			item.setFiles(fundPlanQueryDAO.queryFileListUploadsByCond(fileparam));
		}
		return item;
	}

	@Override
	public ContractProjectInfoVo queryNoticeAndPurchasePlanByProjectId(String jsonStr) {
		// 1.json格式校验
		if (!JsonUtil.jsonValidate(jsonStr)) {
			throw new BaseException(new StringBuffer().append("字符串： ").append(jsonStr).append("不符合JSON格式").toString());
		}
		JSONObject jsonObj = JSONObject.fromObject(jsonStr);
		String errorMsg = "获取入参时：";
		String impleProjId = JsonUtil.getStringFromJSON(jsonObj, "impleProjId", errorMsg);
		String contractId = JsonUtil.getStringFromJSON(jsonObj, "contractId", errorMsg);
		String purchasePlanId = JsonUtil.getStringFromJSON(jsonObj, "purchasePlanId", errorMsg);
		if (StringUtils.isEmpty(impleProjId))
			return null;
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("impleProjId", impleProjId);
		param.put("contractId", contractId);
		param.put("impleProjIds", new String[] { impleProjId });
		ContractProjectInfoVo vo = contractQueryDAO.queryNoticeAndPurchasePlanByProjectId(param);
		if (vo == null) {
			vo = new ContractProjectInfoVo();
			vo.setImpleProjCode(impleProjId);
		}
		List<PurchasePlan> list = purchasePlanQueryDAO.queryPurchasePlanList(param);
		Map<String, String> pmap = new HashMap<String, String>();
		if (list != null) {
			for (int i = 0; i < list.size(); i++) {
				pmap.put(list.get(i).getPurchPlanId(), list.get(i).getPurchPlanName());
			}
		}
			vo.setPurchmap(pmap);

		return vo;
	}

	@Override
	public ContractProjectInfoVo queryNoticeByPurchPlanId(String jsonStr) {
		// 1.json格式校验
		if (!JsonUtil.jsonValidate(jsonStr)) {
			throw new BaseException(new StringBuffer().append("字符串： ").append(jsonStr).append("不符合JSON格式").toString());
		}
		JSONObject jsonObj = JSONObject.fromObject(jsonStr);
		String errorMsg = "获取入参时：";
		String purchasePlanId = JsonUtil.getStringFromJSON(jsonObj, "purchPlanId", errorMsg);
		if (StringUtils.isEmpty(purchasePlanId))
			return null;
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("purchasePlanId", purchasePlanId);
		ContractProjectInfoVo vo = contractQueryDAO.queryNoticeByPurchPlanId(param);
		return vo;
	}

	public boolean existContractClause(String contractId) {
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("contractId", contractId);
		System.out.println("contractClauseQueryDAO====="+contractClauseQueryDAO);
		ContractClause contractClause = contractClauseQueryDAO.queryContractClause(param);
		if (contractClause != null) {
			return  true;
		}
		return false;
	}
}
